<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑企业信息</view>
      <view class="nav-right"></view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 公司品牌信息标题 -->
      <view class="brand-header">
        <text class="brand-title">公司品牌信息</text>
        <text class="brand-tip">完善公司信息，可以获得更多求职者的信赖与兴趣</text>
        <view class="completion-info">
          <text class="completion-text">信息完善度</text>
          <view class="completion-bar">
            <view class="completion-progress" :style="{ width: completionRate + '%' }"></view>
          </view>
          <text class="completion-rate">{{ completionRate }}%</text>
        </view>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 基本信息 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="基本信息" 
            @click="goToBasicInfo"
          />
        </uni-list>

        <!-- 公司性质 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="公司性质" 
            @click="goToEditCompanyNature"
          />
        </uni-list>

        <!-- 公司相册 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="公司相册" 
            @click="goToUploadPhotos"
          />
        </uni-list>

        <!-- 工作时间 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="工作时间" 
            @click="goToEditWorkTime"
          />
        </uni-list>

        <!-- 公司优势 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="公司优势" 
            @click="goToCompanyAdvantage"
          />
        </uni-list>

        <!-- 工商信息 -->
        <uni-list>
          <uni-list-item 
            :clickable="true"
            showArrow 
            title="工商信息" 
            @click="goToCompanyBusiness"
          />
        </uni-list>
      </view>














    </view>


  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { getMyBindCompanyDetailApi } from "@/api/company.js";






// 公司数据
const companyInfo = ref({
  id: '',
  companyName: '',
  shortName: '',
  logo: '',
  country: '',
  province: '',
  city: '',
  district: '',
  address: '',
  nature: '',
  peopleSize: '',
  industry: '',
  financStage: '',
  workTime: '',
  introduction: '',
  advantage: '',
  benefits: '',
  bonus: '',
  subsidy: ''
});

// 表单数据
const formData = ref({
  logo: '',
  shortName: '',
  industry: '',
  nature: '',
  peopleSize: '',
  address: '',
  introduction: '',
  workStartTime: '',
  workEndTime: '',
  overtimeSituation: '',
  restTime: '',
  advantage: [],      // 存储字典数据ID
  benefits: [],       // 存储字典数据ID
  bonus: [],          // 存储字典数据ID
  subsidy: [],        // 存储字典数据ID
  photos: [],         // 新增：存储公司相册照片URL数组
  buildDate: '',      // 成立时间
  registCapital: '',  // 注册资本
  registPlace: '',    // 注册地址
  legalRepresentative: '', // 法人代表
  financStage: ''     // 融资阶段
});

// 当前相册照片列表
const currentPhotos = ref([]);


const onAdvantageSuccess = (data) => {
  // 更新本地数据
  formData.value.advantage = data.advantage;
  formData.value.benefits = data.benefits;
  formData.value.bonus = data.bonus;
  formData.value.subsidy = data.subsidy;
  
  // 发送事件通知公司详情页面重新获取数据
  uni.$emit('companyInfoUpdated');
};
// 跳转到基本信息编辑页面
const goToBasicInfo = () => {
  uni.navigateTo({
    url: `/pages/company/companyEdit/basicInfoEdit?companyId=${companyInfo.value.id}&companyName=${encodeURIComponent(companyInfo.value.companyName || '')}&logo=${encodeURIComponent(formData.value.logo || '')}&shortName=${encodeURIComponent(formData.value.shortName || '')}&address=${encodeURIComponent(formData.value.address || '')}&introduction=${encodeURIComponent(formData.value.introduction || '')}`
  });
};

// 跳转到上传相册页面
const goToUploadPhotos = () => {
  const photosParam = encodeURIComponent(currentPhotos.value.join(','));
  uni.navigateTo({
    url: `/pages/company/uploadPhotos?companyId=${companyInfo.value.id}&photos=${photosParam}`
  });
};

// 跳转到编辑工作时间页面
const goToEditWorkTime = () => {
  uni.navigateTo({
    url: `/pages/company/companyEdit/editWorkTime?companyId=${companyInfo.value.id}&workStartTime=${encodeURIComponent(formData.value.workStartTime || '')}&workEndTime=${encodeURIComponent(formData.value.workEndTime || '')}&overtimeSituation=${encodeURIComponent(formData.value.overtimeSituation || '')}&restTime=${encodeURIComponent(formData.value.restTime || '')}`
  });
};

// 跳转到编辑公司性质页面
const goToEditCompanyNature = () => {
  uni.navigateTo({
    url: `/pages/company/companyEdit/editCompanyNature?companyId=${companyInfo.value.id}&industry=${encodeURIComponent(formData.value.industry || '')}&nature=${encodeURIComponent(formData.value.nature || '')}&peopleSize=${encodeURIComponent(formData.value.peopleSize || '')}`
  });
};

// 跳转到编辑公司优势页面
const goToCompanyAdvantage = () => {
  uni.navigateTo({
    url: `/pages/company/companyEdit/companyAdvantage?companyId=${companyInfo.value.id}&advantage=${encodeURIComponent(formData.value.advantage.join(' ') || '')}&benefits=${encodeURIComponent(formData.value.benefits.join(' ') || '')}&bonus=${encodeURIComponent(formData.value.bonus.join(' ') || '')}&subsidy=${encodeURIComponent(formData.value.subsidy.join(' ') || '')}`
  });
};

// 跳转到编辑工商信息页面
const goToCompanyBusiness = () => {
  uni.navigateTo({
    url: `/pages/company/companyEdit/companyBusiness?companyId=${companyInfo.value.id}&buildDate=${encodeURIComponent(formData.value.buildDate || '')}&registCapital=${encodeURIComponent(formData.value.registCapital || '')}&registPlace=${encodeURIComponent(formData.value.registPlace || '')}&legalRepresentative=${encodeURIComponent(formData.value.legalRepresentative || '')}&financStage=${encodeURIComponent(formData.value.financStage || '')}`
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取公司详情
const getCompanyDetail = async () => {
  try {
    const companyData = await getMyBindCompanyDetailApi();
    if (companyData) {
      companyInfo.value = companyData;
      // 同步表单数据
      formData.value = {
        logo: companyData.logo || '',
        shortName: companyData.shortName || '',
        industry: companyData.industry || '',
        nature: companyData.nature || '',
        peopleSize: companyData.peopleSize || '',
        address: companyData.address || '',
        introduction: companyData.introduction || '',
        workStartTime: companyData.workStartTime || '',
        workEndTime: companyData.workEndTime || '',
        overtimeSituation: companyData.overtimeSituation || '',
        restTime: companyData.restTime || '',
        advantage: companyData.advantage ? (Array.isArray(companyData.advantage) ? companyData.advantage : []) : [],
        benefits: companyData.benefits ? (Array.isArray(companyData.benefits) ? companyData.benefits : []) : [],
        bonus: companyData.bonus ? (Array.isArray(companyData.bonus) ? companyData.bonus : []) : [],
        subsidy: companyData.subsidy ? (Array.isArray(companyData.subsidy) ? companyData.subsidy : []) : [],
        photos: companyData.photos ? (Array.isArray(companyData.photos) ? companyData.photos : []) : [] // 同步相册照片
      };
      
      // 处理工作时间字段：如果是字符串，则解析为各个字段
      if (companyData.workTime && typeof companyData.workTime === 'string') {
        const workTimeParts = companyData.workTime.split(' ');
        if (workTimeParts.length >= 1) {
          const timeRange = workTimeParts[0];
          const timeRangeParts = timeRange.split('-');
          if (timeRangeParts.length === 2) {
            formData.value.workStartTime = timeRangeParts[0];
            formData.value.workEndTime = timeRangeParts[1];
          }
        }
        if (workTimeParts.length >= 2) {
          formData.value.overtimeSituation = workTimeParts[1];
        }
        if (workTimeParts.length >= 3) {
          formData.value.restTime = workTimeParts[2];
        }
      }
      
      // 处理优势相关字段：如果是字符串，则按空格分割
      if (companyData.advantage && typeof companyData.advantage === 'string') {
        formData.value.advantage = companyData.advantage.split(' ').filter(item => item.trim());
      }
      if (companyData.benefits && typeof companyData.benefits === 'string') {
        formData.value.benefits = companyData.benefits.split(' ').filter(item => item.trim());
      }
      if (companyData.bonus && typeof companyData.bonus === 'string') {
        formData.value.bonus = companyData.bonus.split(' ').filter(item => item.trim());
      }
      if (companyData.subsidy && typeof companyData.subsidy === 'string') {
        formData.value.subsidy = companyData.subsidy.split(' ').filter(item => item.trim());
      }
      
      // 处理photos字段：如果是字符串，则按逗号分割
      if (companyData.photos && typeof companyData.photos === 'string') {
        currentPhotos.value = companyData.photos.split(',').filter(url => url.trim());
      } else if (Array.isArray(companyData.photos)) {
        currentPhotos.value = companyData.photos;
      } else {
        currentPhotos.value = [];
      }
      
      // 同步工商信息字段
      formData.value.buildDate = companyData.buildDate || '';
      formData.value.registCapital = companyData.registCapital || '';
      formData.value.registPlace = companyData.registPlace || '';
      formData.value.legalRepresentative = companyData.legalRepresentative || '';
      formData.value.financStage = companyData.financStage || '';

    }
  } catch (error) {
    console.error('获取公司详情失败:', error);
    uni.showToast({
      title: '获取公司信息失败',
      icon: 'none'
    });
  }
};



// 信息完善度计算
const completionRate = computed(() => {
  // 检查每个字段是否已填写
  const logoStatus = formData.value.logo && formData.value.logo.trim();
  const shortNameStatus = formData.value.shortName && formData.value.shortName.trim();
  const industryStatus = formData.value.industry && formData.value.industry.trim();
  const natureStatus = formData.value.nature && formData.value.nature.trim();
  const peopleSizeStatus = formData.value.peopleSize && formData.value.peopleSize.trim();
  const addressStatus = formData.value.address && formData.value.address.trim();
  const introductionStatus = formData.value.introduction && formData.value.introduction.trim();
  const workStartTimeStatus = formData.value.workStartTime && formData.value.workStartTime.trim();
  const workEndTimeStatus = formData.value.workEndTime && formData.value.workEndTime.trim();
  const overtimeSituationStatus = formData.value.overtimeSituation && formData.value.overtimeSituation.trim();
  const restTimeStatus = formData.value.restTime && formData.value.restTime.trim();
  const advantageStatus = formData.value.advantage && Array.isArray(formData.value.advantage) && formData.value.advantage.length > 0;
  const benefitsStatus = formData.value.benefits && Array.isArray(formData.value.benefits) && formData.value.benefits.length > 0;
  const bonusStatus = formData.value.bonus && Array.isArray(formData.value.bonus) && formData.value.bonus.length > 0;
  const subsidyStatus = formData.value.subsidy && Array.isArray(formData.value.subsidy) && formData.value.subsidy.length > 0;
  const photosStatus = currentPhotos.value && Array.isArray(currentPhotos.value) && currentPhotos.value.length > 0;
  
  // 工商信息字段状态
  const buildDateStatus = formData.value.buildDate && formData.value.buildDate.trim();
  const registCapitalStatus = formData.value.registCapital && formData.value.registCapital.trim();
  const registPlaceStatus = formData.value.registPlace && formData.value.registPlace.trim();
  const legalRepresentativeStatus = formData.value.legalRepresentative && formData.value.legalRepresentative.trim();
  const financStageStatus = formData.value.financStage && formData.value.financStage.trim();
  
  // 计算完成的字段数量
  let completedFields = 0;
  if (logoStatus) completedFields++;
  if (shortNameStatus) completedFields++;
  if (industryStatus) completedFields++;
  if (natureStatus) completedFields++;
  if (peopleSizeStatus) completedFields++;
  if (addressStatus) completedFields++;
  if (introductionStatus) completedFields++;
  if (workStartTimeStatus) completedFields++;
  if (workEndTimeStatus) completedFields++;
  if (overtimeSituationStatus) completedFields++;
  if (restTimeStatus) completedFields++;
  if (advantageStatus) completedFields++;
  if (benefitsStatus) completedFields++;
  if (bonusStatus) completedFields++;
  if (subsidyStatus) completedFields++;
  if (photosStatus) completedFields++;
  if (buildDateStatus) completedFields++;
  if (registCapitalStatus) completedFields++;
  if (registPlaceStatus) completedFields++;
  if (legalRepresentativeStatus) completedFields++;
  if (financStageStatus) completedFields++;
  
  const totalFields = 21; // 实际字段数：logo、简称、行业、公司性质、人员规模、地址、介绍、上班时间、下班时间、加班情况、休息时间、优势、福利、薪资、补助、相册、成立时间、注册资本、注册地址、法人代表、融资阶段
  
  return Math.round((completedFields / totalFields) * 100);
});




onMounted(async () => {
  try {
    // 获取公司详情
    await getCompanyDetail();
  } catch (error) {
    console.error('页面数据加载失败:', error);
  }
  
  // 监听企业信息更新事件
  uni.$on('companyInfoUpdated', handleCompanyInfoUpdated);
});

// 页面显示时重新获取企业信息
uni.$on('onShow', () => {
  getCompanyDetail().catch(error => {
    console.error('页面显示时获取公司信息失败:', error);
  });
});

// 监听页面显示事件
onMounted(() => {
  // 监听页面显示事件
  uni.$on('onShow', () => {
    getCompanyDetail().catch(error => {
      console.error('页面显示时获取公司信息失败:', error);
    });
  });
});



// 处理企业信息更新事件
const handleCompanyInfoUpdated = () => {
  console.log('收到企业信息更新事件，重新获取数据');
  getCompanyDetail().catch(error => {
    console.error('事件触发后获取公司信息失败:', error);
  });
};

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('companyInfoUpdated', handleCompanyInfoUpdated);
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 60rpx;
  height: 60rpx;
}

.container {
  padding: 20rpx;
}

/* 公司品牌信息标题样式 */
.brand-header {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.brand-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.brand-tip {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  display: block;
  margin-bottom: 40rpx;
}

.completion-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.completion-text {
  font-size: 28rpx;
  color: #333;
}

.completion-bar {
  width: 200rpx;
  height: 12rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
  overflow: hidden;
}

.completion-progress {
  height: 100%;
  background: linear-gradient(90deg, #007aff, #00bdb4);
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

.completion-rate {
  font-size: 28rpx;
  color: #007aff;
  font-weight: bold;
  min-width: 60rpx;
}

/* 表单区域样式 */
.form-section {
  background-color: transparent;
  border-radius: 8rpx;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

/* uni-collapse 组件样式优化 */
:deep(.uni-collapse) {
  border: none;
  background: transparent;
  margin: 0;
  padding: 0;
}

:deep(.uni-collapse-item) {
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 0;
  background: #fff;
  border-radius: 0;
  overflow: hidden;
}

:deep(.uni-collapse-item:last-child) {
  border-bottom: none;
}

:deep(.uni-collapse-item__title) {
  background-color: #fafafa;
  padding: 30rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  border: none;
  margin: 0;
  position: relative;
  transition: all 0.3s ease;
}

:deep(.uni-collapse-item__title--active) {
  background-color: #f0f8ff;
  color: #007aff;
  border-bottom: 2rpx solid #007aff;
}

:deep(.uni-collapse-item__content) {
  background-color: #fff;
  padding: 0;
  margin: 0;
  border: none;
}

:deep(.uni-collapse-item__content-box) {
  padding: 0;
  margin: 0;
  border: none;
}

:deep(.uni-collapse-item__arrow) {
  color: #999;
  font-size: 28rpx;
  transition: transform 0.3s ease;
}

:deep(.uni-collapse-item__arrow--active) {
  color: #007aff;
  transform: rotate(180deg);
}

/* 优化表单项样式 */
.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.form-input {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
  min-height: 80rpx;
  padding: 12rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  display: block;
  position: relative;
  z-index: 1;
}

.form-input:focus {
  border-color: #007aff;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.form-textarea {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
  min-height: 120rpx;
  line-height: 1.5;
  padding: 12rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  resize: none;
  display: block;
  position: relative;
  z-index: 1;
}

.form-textarea:focus {
  border-color: #007aff;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.form-value {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.form-value.fixed {
  color: #999;
}

.picker-value {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 48rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.picker-text {
  flex: 1;
  margin-right: 20rpx;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: calc(100% - 60rpx);
}

.picker-value .arrow {
  color: #999;
  font-size: 28rpx;
  flex-shrink: 0;
  margin-left: 10rpx;
}

.picker-value.disabled {
  color: #999;
}





/* LOGO上传样式 */
.upload-section {
  width: 100%;
  min-height: 120rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  box-sizing: border-box;
}

.upload-image {
  width: 100%;
  height: 120rpx;
  object-fit: contain;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-text {
  font-size: 28rpx;
}

.arrow {
  color: #999;
  font-size: 28rpx;
}



/* 加载状态和错误处理样式 */
.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120rpx; /* 与上传区域高度一致 */
  background-color: #f5f5f5;
  border-radius: 8rpx;
  border: 2rpx dashed #ddd;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}



/* 弹窗样式 */
.popup-content {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 50%;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-close:hover {
  color: #333;
  background-color: #f5f5f5;
}

.popup-body {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 0 30rpx 30rpx;
  max-height: 90vh;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

/* uni-list 样式优化 */
:deep(.uni-list) {
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

:deep(.uni-list-item) {
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

:deep(.uni-list-item:last-child) {
  border-bottom: none;
}

:deep(.uni-list-item__content) {
  padding: 30rpx;
}

:deep(.uni-list-item__content-title) {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

:deep(.uni-list-item__content-right) {
  font-size: 24rpx;
  color: #666;
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.uni-list-item__content-arrow) {
  color: #999;
  margin-left: 10rpx;
}


</style>
